﻿using UnityEngine;
using System.Collections;
using Helper;

public class ParticleMove : MonoBehaviour {
	[SerializeField] ParticleSystem particleSys;
	[SerializeField] Transform targetPos;
	[SerializeField] float moveTimeRate = 3f;
	[SerializeField] float periodNum = 3f;
	[SerializeField] float amplitude = 1f;
	//粒子运动开始的时间
	[SerializeField] float startTime = 0.5f;
	int count = -1;
	ParticleSystemRenderer parSysRenderer;
	ParticleSystem.Particle[] regionParticlesPos;
	float lastTime = 0f;
	// Use this for initialization
	void Start () {
		particleSys = GetComponent<ParticleSystem> ();
		parSysRenderer = particleSys.GetComponent<ParticleSystemRenderer> ();
	}
	
	// Update is called once per frame
	void Update () {
		int particlesNum = particleSys.particleCount;
		ParticleSystem.Particle[] particles = new ParticleSystem.Particle[particlesNum];
		particleSys.GetParticles (particles);
		lastTime = particles.Length > 0 ? particles [0].startLifetime - particles [0].lifetime : 0f;
		bool isStartMoving = (lastTime >= startTime);
		//if (count < temp && isStartMoving) {
		//	count = temp;
		//	ParticleSystem.Particle[] regionParticlesPos = new ParticleSystem.Particle[particlesNum];
		//	particleSys.GetParticles (regionParticlesPos);
		//}
		parSysRenderer.renderMode = isStartMoving ? ParticleSystemRenderMode.Stretch : ParticleSystemRenderMode.Billboard;
		//print (particles.Length - regionParticlesPos.Length);
		if(!isStartMoving){
			return;
		}
		for(int i = 0; i<particlesNum; i++) {
				Vector3 curPos = MyTween.GetPosInSin(particles[i].position, targetPos.position,
					periodNum / moveTimeRate * (1f - particles[i].lifetime / particles[i].startLifetime),
					amplitude: amplitude, periodNum: periodNum);
				particles [i].velocity = (curPos - particles [i].position) / Time.deltaTime;
				particles [i].position = curPos;
		}
		particleSys.SetParticles (particles, particlesNum);
	}
}
